// 监听扩展图标点击事件
chrome.action.onClicked.addListener((tab) => {
    // 先保存当前标签页信息
    const currentTabInfo = {
        title: tab.title,
        url: tab.url,
        hostname: new URL(tab.url).hostname,
        timestamp: new Date().toISOString()
    };

    // 将当前标签页信息保存到存储中
    chrome.storage.local.set({ 'currentSourceTab': currentTabInfo }, () => {
        // 打开新的标签页显示仪表板
        chrome.tabs.create({
            url: chrome.runtime.getURL('dashboard.html')
        });
    });
});

// 存储来源信息的对象
let sourceRecords = new Map();

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'recordSource') {
        const sourceTab = message.sourceTab;
        const targetTab = message.targetTab;
        const targetWindow = message.targetWindow;

        if (sourceTab && (targetTab || targetWindow)) {
            const sourceInfo = {
                title: sourceTab.title,
                url: sourceTab.url,
                hostname: new URL(sourceTab.url).hostname,
                timestamp: new Date().toISOString()
            };

            // 记录来源信息
            if (targetTab) {
                sourceRecords.set(targetTab.id, sourceInfo);
                // 同时保存到存储中以便 dashboard 访问
                saveSourceRecordToStorage(targetTab.id, sourceInfo);
            } else if (targetWindow) {
                // 对于新窗口，我们需要等待标签页创建完成
                chrome.tabs.query({ windowId: targetWindow.id }, (tabs) => {
                    if (tabs.length > 0) {
                        sourceRecords.set(tabs[0].id, sourceInfo);
                        // 同时保存到存储中以便 dashboard 访问
                        saveSourceRecordToStorage(tabs[0].id, sourceInfo);
                    }
                });
            }
        }
    } else if (message.action === 'getSourceRecords') {
        // 返回所有来源记录给 dashboard
        chrome.storage.local.get(['sourceHistory'], (result) => {
            sendResponse({ sourceHistory: result.sourceHistory || [] });
        });
        return true; // 保持消息通道开放以进行异步响应
    }
});

// 保存来源记录到存储
function saveSourceRecordToStorage(tabId, sourceInfo) {
    chrome.storage.local.get(['sourceHistory'], (result) => {
        let sourceHistory = result.sourceHistory || [];
        const recordWithTabId = {...sourceInfo, tabId: tabId };

        // 检查是否已存在相同的记录
        const existingIndex = sourceHistory.findIndex(record =>
            record.url === sourceInfo.url && record.timestamp === sourceInfo.timestamp
        );

        if (existingIndex === -1) {
            // 添加新记录到开头
            sourceHistory.unshift(recordWithTabId);

            // 限制记录数量（最多保存 100 条）
            if (sourceHistory.length > 100) {
                sourceHistory = sourceHistory.slice(0, 100);
            }

            // 保存到存储
            chrome.storage.local.set({ sourceHistory: sourceHistory });
        }
    });
}

// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && sourceRecords.has(tabId)) {
        // 当新标签页加载完成时，注入内容脚本显示来源信息
        chrome.scripting.executeScript({
            target: { tabId: tabId },
            func: showSourceInfo,
            args: [sourceRecords.get(tabId)]
        });
    }
});

// 监听标签页关闭事件，清理记录
chrome.tabs.onRemoved.addListener((tabId) => {
    sourceRecords.delete(tabId);
});

// 在页面中显示来源信息的函数
function showSourceInfo(sourceInfo) {
    // 创建来源信息显示框
    const overlay = document.createElement('div');
    overlay.id = 'source-info-overlay';
    overlay.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        max-width: 300px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        font-size: 14px;
        line-height: 1.4;
        animation: slideIn 0.5s ease-out;
    `;

    overlay.innerHTML = `
        <div style="margin-bottom: 10px; font-weight: 600; font-size: 16px;">
            📍 来源网站
        </div>
        <div style="margin-bottom: 8px;">
            <strong>标题:</strong> ${sourceInfo.title}
        </div>
        <div style="margin-bottom: 8px;">
            <strong>域名:</strong> ${sourceInfo.hostname}
        </div>
        <div style="margin-bottom: 10px; font-size: 12px; opacity: 0.8;">
            ${new Date(sourceInfo.timestamp).toLocaleString('zh-CN')}
        </div>
        <button id="close-source-info" style="
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        ">关闭</button>
    `;

    // 添加 CSS 动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    `;
    document.head.appendChild(style);

    // 添加到页面
    document.body.appendChild(overlay);

    // 添加关闭按钮事件
    document.getElementById('close-source-info').addEventListener('click', () => {
        overlay.remove();
    });

    // 5 秒后自动隐藏
    setTimeout(() => {
        if (overlay.parentNode) {
            overlay.style.animation = 'slideOut 0.5s ease-in forwards';
            setTimeout(() => {
                if (overlay.parentNode) {
                    overlay.remove();
                }
            }, 500);
        }
    }, 5000);

    // 添加滑出动画
    const slideOutStyle = document.createElement('style');
    slideOutStyle.textContent = `
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(slideOutStyle);
}

// 监听扩展安装事件
chrome.runtime.onInstalled.addListener(() => {
    console.log('网站来源查看器已安装');
});